package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.LinkedList;
import java.util.Queue;

public class CycleDetection {

    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private boolean hasCycle = false;

    public CycleDetection(Graph G) {
        this.G = G;
        visited = new boolean[G.V()];
        pre = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            pre[i] = -1;
        }
        for (int v = 0; v < G.V(); v++) {
            if (!visited[v]) {
                if (bfs(v, v)) hasCycle = true;
                break;
            }
        }
    }

    private boolean bfs(int v, int p) {
        Queue<Integer> queue = new LinkedList<>();
        visited[v] = true;
        pre[v] = p;
        queue.add(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            for (Integer w : G.adj(cur)) {
                if (!visited[w]) {
                    visited[w] = true;
                    pre[w] = cur;
                    queue.add(w);
                } else if (pre[cur] != w) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean hasCycle() {
        return hasCycle;
    }

    public static void main(String[] args) {
        String filename = CycleDetection.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CycleDetection cycleDetection = new CycleDetection(g);
        System.out.println(cycleDetection.hasCycle());

        String filename2 = CycleDetection.class.getClassLoader().getResource("g2.txt").getPath();
        Graph g2 = new Graph(filename2);
        CycleDetection cycleDetection2 = new CycleDetection(g2);
        System.out.println(cycleDetection2.hasCycle());
    }
}
